<!--
 * @FileDescription: 主页组件
 * @Author: yijiamu
 * @Date: 2022-05-08 19:58:15
 * @LastEditors: yijiamu
 * @LastEditTime: 2022-05-08 19:58:15
 -->
<template>
  <div class="msite" id="miste">
    <header>
      <section class="info-container">
        <router-link to="/choiceCity" slot="msite-title" class="info-position">
          <span class="position-title">
            {{msiteTitle}}<i class="el-icon-caret-bottom"></i>
          </span>
        </router-link>
        <div class="info-message">
          <i class="el-icon-shopping-cart-2 info-icon"></i>
          <i class="el-icon-chat-line-square info-icon"></i>
        </div>
      </section >
      <router-link :to="{path: 'searchShop', query:{geohash}}">
        <section class="search-container">
          <el-form>
            <el-input
              placeholder="想吃点什么呢？"
              prefix-icon="el-icon-full-screen">
            </el-input>
          </el-form>
        </section>
      </router-link>
    </header>
    <!--category-->
    <section class="category-container swiper-container">
      <nav class="category-primary swiper-wrapper">
        <div class=" category-primary-list swiper-slide">
          <li class="category-primary-item" v-for="(item, index) in foodTypes[0]" :key="index">
            <!--          <router-link :to="{path: '/food', query: {geohash, title: foodItem.title, restaurant_category_id: getCategoryId(foodItem.link)}}" v-for="foodItem in item" :key="foodItem.id" class="link_to_food">-->
            <img :src="imgBaseUrl + item.image_url" class="category-primary-cover">
            <hgroup class="category-primary-title">{{item.title}}</hgroup>
            <!--          </router-link>-->
          </li>
        </div>
        <div class="category-primary-list swiper-slide">
          <li class="category-primary-item" v-for="(item, index) in foodTypes[1]" :key="index">
            <!--          <router-link :to="{path: '/food', query: {geohash, title: foodItem.title, restaurant_category_id: getCategoryId(foodItem.link)}}" v-for="foodItem in item" :key="foodItem.id" class="link_to_food">-->
            <img :src="imgBaseUrl + item.image_url" class="category-primary-cover">
            <hgroup class="category-primary-title">{{item.title}}</hgroup>
            <!--          </router-link>-->
          </li>
        </div>
      </nav>
      <div class="swiper-pagination"></div>
    </section>
    <!--main-->
    <main class="main-container">
      <h3 class="main-title">附近推荐</h3>
      <section class="type-bread" @click="addToSupportSelector($event)">
        <button class="bread" >外卖保</button>
        <button class="bread" >准时达</button>
        <button class="bread" >开发票</button>
      </section>
      <shop-list-com
        v-if="shopList.length"
        :shopListArr="shopList"
        :geohash="geohash"/>
    </main>
  <footerCom :isClick="1"></footerCom>
  </div>
</template>

<script lang="ts">
import { Component , Vue, Watch } from 'vue-property-decorator';
import {reqFoodTypes} from "@/api/food";
import {reqShopList} from "@/api/shop";
import {IfoodTypes, IShopList, IshopListQuery} from "@/api/config/responseType";
import Swiper from 'swiper';
import 'swiper/css/swiper.css'
import 'swiper/js/swiper.min.js'
import _, {} from 'lodash';
import {getClientHeight, getScrollHeight, getScrollTop } from '@/utils/utils';
//Vuex
import {AxiosError, AxiosResponse} from "axios";
import { State, Action, Getter } from "vuex-class";
const namespace = "profile"
@Component({components: {}})
export default class homeCom extends Vue {
  private foodTypes = [] as IfoodTypes[][];   //食物分类
  private imgBaseUrl = 'https://fuss10.elemecdn.com' as string //图片域名地址
  private supportSelector = [] as string[]  //面包屑分类
  private shopList = [] as IShopList[];  //请求得到的全部店铺列表
  private shopListQuery = {} as IshopListQuery;  //请求全部店铺列表的参数
  private shopListNumber = 20 as number ;   //店铺数据的数量
  private touchend = false as boolean ; //是否以及加载完毕
  @State('geohash' , { namespace }) geohash !: string |(string | null)[]; //当前定位
  @State('pois' , { namespace }) msiteTitle !: string ; //定位名称
  @Action('setGeoHash', { namespace }) setGeoHash: any  //如果Vuex中没有，则获取一个新的并交给仓库
  @Action('setPosi', { namespace }) setPosi: any  //如果Vuex中没有，则获取一个新的并交给仓库
  async beforeMount(){
    //如果仓库里面没有定位，则重新设定一个
    if (!this.geohash) {
      await this.setGeoHash();
    }
    await this.setPosi(); //设置当前位置名
    await this.loadReqQuery(this.shopListNumber);
    await this.getFoodTypes();
    await this.getAllShopList();
    window.addEventListener('scroll',this.handleScroll)
  }
  @Watch('geohash')
  onGeoHashChanged(){
    this.setPosi(); //设置当前位置名
  }
/**
 * @description:获取主页的分类
 * @return {}
 */
  private getFoodTypes(){
    reqFoodTypes().then(res => {
      let resLength = res.data.length;
      let resArr = [...res.data]; // 返回一个新的数组
      let foodArr = [];
      for (let i = 0, j = 0; i < resLength; i += 8, j++) {
        foodArr[j] = resArr.splice(0, 8);
      }
      this.foodTypes = foodArr;
    }).then(() => {
      // 初始化swiper
      new Swiper('.swiper-container', {
        pagination: {
          el: '.swiper-pagination',
        },
        loop: true,
      });
    })
  }
/**
 * @description:获取附件推荐的分类
 * @return {}
 */
  private addToSupportSelector(e:any){
    if(!this.supportSelector.includes(e.target.innerText)){
      this.supportSelector.push(e.target.innerText);
      e.target.classList.add('active');
    }else{
      this.supportSelector = this.supportSelector.filter((item)=>{
        return item === 'name'
      })
      e.target.classList.remove('active');
    }
  }
/**
 * @description:初始化参数
 * @return {}
 */
  private loadReqQuery(limit:number){
    this.shopListQuery = {
        latitude : JSON.stringify(this.geohash).split(',')[0].replace("\"",''),
        longitude : JSON.stringify(this.geohash).split(',')[1].replace("\"",''),
        offset : 0,
        limit : limit,
        restaurant_category_id : undefined,
        order_by : undefined,
        // delivery_mode : '',
        // support_ids : undefined,
        restaurant_category_ids : undefined,
    }
  }
/**
 * @description:请求的全部店铺列表
 * @return {}
 */
  private async getAllShopList(){
    await reqShopList(this.shopListQuery).then((res:AxiosResponse)=>{
      let resShopList = res.data;
      if(resShopList.length < 20){
        this.touchend = true;
      }
      this.shopList = resShopList;
    },(err:AxiosError)=>{
      console.log(err)
    })
  }
/**
  * @description: 当用户滑到最后时，新加载十条数据，使用防抖，防止用户一直滑动更改offset
  * @return {}
  */
  private handleScroll = _.throttle(()=>{
    if (getScrollTop() + getClientHeight() == getScrollHeight()) {
      if (!this.touchend) {
        this.shopListNumber += 10;
      }
      this.loadReqQuery(this.shopListNumber);
      this.getAllShopList()
    }
  },500)
/**
  * @description: 监控supportSelector筛选数据
  * @return {}
  */
  @Watch('supportSelector')
  selectSupport(){
    if(this.supportSelector != undefined){
      this.shopList = this.shopList.filter((shop)=>{
        let shopSelect:string[] = [];
        shop.supports.forEach(item=>{
          shopSelect.push(item.name);
        })
        let res:boolean = this.supportSelector.every(select=>{
          return shopSelect.includes(select);
        })
        return res
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
html {
  scroll-behavior: smooth;
}
.msite {
  ul,ol,li {
    list-style: none;
  }
  a {
    text-decoration: none;
    color: black;
  }
  .router-link-active {
    text-decoration: none;
    color: black;
  }
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
  //header
  header {
    padding: 0 6px;
    background-color: #ffffff;
    .info-container {
      margin: 0 10px;
      padding: 12px 0 ;
      display: flex;
      justify-content: space-between;
      .info-position {
        .position-title {
          margin: 0;
          font-weight: bold;
        }
      }
      .info-message {
        white-space: nowrap;
        .info-icon {
          font-size: 1.5em;
          margin: 0 6px;
          font-weight: bold;
        }
      }
    }
    .search-container {
      text-align:center;
      position: relative;
      .el-form {
        padding: 2vw 2vw;
        //第二步：添加 >>> ,若是使用less等预处理器，可将>>>修改为/deep/
        /deep/.el-input__inner {
          font-size: 14px;
          //width: 80%;
          padding-left: 3em;
          vertical-align: center;
          border: #5ec2f8 2px solid;
          border-radius: 30px
        }
        /deep/.el-input__icon {
          margin-left: 1vw;
          color: #5ec2f8;
          font-size: 1.5em;
        }
      }
      .el-icon-full-screen {
        position: absolute;
        left: 0.8em;
        top: 0.35em;
        color: #5ec2f8;
        font-size: 1.5em;
      }
      .search {
        background: linear-gradient(#61c6fa, #4dabf0);
        color: white;
        font-size: 14px;
        font-weight: bold;
        position: absolute;
        top: 0;
        right: 0;
        text-align:center;
        vertical-align: center;
        padding: 8.3px 1.3em ;
        border: #5ec2f8 2px solid;
        border-radius: 30px
      }
    }
  }
  //category
  .category-container {
    .swiper-pagination {
      bottom: -4px;
    }
    padding: 16px 8px 0 8px;
    font-size: 14px;
    background: linear-gradient(#ffffff, #f5f5f5);
    li {
      list-style: none;
    }
    .category-primary {
      width: 100%;
      display: flex;
      .category-primary-list {
        display: flex;
        flex-wrap: wrap;
        .category-primary-item {
          margin:6px 0 ;
          display: flex;
          flex-direction: column;
          align-items: center;
          width: 25%;
          .category-primary-cover{
            width: 75%;
          }
          .category-primary-title{
            text-align: center;
            vertical-align: center;
          }
        }
      }

    }
  }
  //main
  .main-container {
    font-size: 16px;
    .main-title {
      margin: 12px 12px;
    }
    .type-bread {
      position: sticky;
      position: -webkit-sticky; /* Safari */
      top: 0;
      padding: 12px;
      background-color: #f5f5f5;
      .bread {
        margin-right: 2vw;
        border: none;
        width: auto;
        background-color: #ffffff;
        border-radius: 10px;
        padding: 0.5em 1.8em;
      }
      .active {
        background-color: #4dabf0;
        color: white;
      }
    }
  }

}
</style>
